package com.xujf.demo.base

import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.os.PersistableBundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.r0adkll.slidr.Slidr
import com.r0adkll.slidr.model.SlidrConfig
import com.r0adkll.slidr.model.SlidrInterface
import com.xujf.demo.ui.view.CustomToast
import com.xujf.demo.ui.view.LoadingProgress

/**
 * Created by xujf on 2018/2/5.
 * 基础标准类
 */
abstract class BaseActivity : AppCompatActivity() {

    private var mDialog: LoadingProgress? = null
    private var slidrInterface: SlidrInterface? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initSlidable()
    }

    /**
     * 初始化滑动返回,禁用需重写空实现
     */
    open fun initSlidable() {
//        val isSlidable = SettingUtil.getInstance().getSlidable()
//        if (isSlidable != Constant.SLIDABLE_DISABLE) {
            val config = SlidrConfig.Builder()
//                    .edge(isSlidable == Constant.SLIDABLE_EDGE)
                    .edge(true) //边缘返回
                    .build()
            slidrInterface = Slidr.attach(this, config)
//        }
    }

    fun showToast(msg: String) {
        CustomToast.showToast(this@BaseActivity, msg, Toast.LENGTH_SHORT)
    }

    fun showToastLong(msg: String) {
        CustomToast.showToast(this@BaseActivity, msg, Toast.LENGTH_LONG)
    }

    fun showLoading(msg: String) {
        if (Build.VERSION.SDK_INT < 17 || Build.VERSION.SDK_INT >= 17 && !isDestroyed) {
            if (mDialog == null) {
                mDialog = LoadingProgress.createDialog(getSuperActivity(this))
                mDialog!!.setOwnerActivity(this)
                mDialog!!.setCancelable(true)
                mDialog!!.setCanceledOnTouchOutside(true)
            }
            mDialog!!.setMessage(msg)
            if (!mDialog!!.isShowing && !this.isFinishing) {
                mDialog!!.show()
            }
        }
    }

    fun hideLoading() {
        if (mDialog != null && mDialog!!.isShowing) {
            mDialog!!.dismiss()
        }
    }

    fun getSuperActivity(activity: Activity): Activity {
        var topActivity: Activity? = activity.parent
        var result = topActivity
        while (topActivity != null) {
            topActivity = topActivity.parent
            if (topActivity != null) {
                result = topActivity
            }
        }
        if (result == null) {
            result = activity
        }
        return result
    }
}